﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Twi.COMMON.HTTP
{
   public class Utils
    {
       /// <summary>
       /// 用户ID
       /// </summary>
       public static string uid = "";

       /// <summary>
       /// 用户名
       /// </summary>
       public static string uname = "";

       /// <summary>
       /// 用户类型
       /// </summary>
       public static string utype = "";

       /// <summary>
       /// 系统版本
       /// </summary>
       public static string version = "";

       public static string GetAbsoluteUrl(string url)
       {
           string apiKey = "";
           if (url.Contains("?"))
           {
               apiKey = "&apikey=" + Config.APIKey();
           }
           else
           {
               apiKey = "?apikey=" + Config.APIKey();
           }
           string _url = Config.ServerAddress() + url + apiKey + string.Format("&uid={0}&uname={1}&utype={2}&version={3}", uid, uname, utype, version);
           return _url;
       }

       /// <summary>
       /// 用于文件服务Url
       /// </summary>
       /// <param name="url">传入示例：http://127.0.0.1/GFile/FileGet...</param>
       /// <returns></returns>
       public static string GetFileAbsoluteUrl(string url)
       {
           string apiKey = "";
           if (url.Contains("?"))
           {
               apiKey = "&apikey=" + Config.APIKey();
           }
           else
           {
               apiKey = "?apikey=" + Config.APIKey();
           }
           string _url = url + apiKey + string.Format("&uid={0}&uname={1}&utype={2}&version={3}", uid, uname, utype, version);
           return _url;
       }



       /// <summary>
       /// 字符串如果操过指定长度则将超出的部分用指定字符串代替
       /// </summary>
       /// <param name="p_SrcString">要检查的字符串</param>
       /// <param name="p_Length">指定长度</param>
       /// <param name="p_TailString">用于替换的字符串</param>
       /// <returns>截取后的字符串</returns>
       public static string GetSubString(string p_SrcString, int p_Length, string p_TailString)
       {
           return GetSubString(p_SrcString, 0, p_Length, p_TailString);
       }

       public static string GetUnicodeSubString(string str, int len, string p_TailString)
       {
           string result = string.Empty;// 最终返回的结果
           int byteLen = System.Text.Encoding.Default.GetByteCount(str);// 单字节字符长度
           int charLen = str.Length;// 把字符平等对待时的字符串长度
           int byteCount = 0;// 记录读取进度
           int pos = 0;// 记录截取位置
           if (byteLen > len)
           {
               for (int i = 0; i < charLen; i++)
               {
                   if (Convert.ToInt32(str.ToCharArray()[i]) > 255)// 按中文字符计算加2
                       byteCount += 2;
                   else// 按英文字符计算加1
                       byteCount += 1;
                   if (byteCount > len)// 超出时只记下上一个有效位置
                   {
                       pos = i;
                       break;
                   }
                   else if (byteCount == len)// 记下当前位置
                   {
                       pos = i + 1;
                       break;
                   }
               }

               if (pos >= 0)
                   result = str.Substring(0, pos) + p_TailString;
           }
           else
               result = str;

           return result;
       }

       /// <summary>
       /// 取指定长度的字符串
       /// </summary>
       /// <param name="p_SrcString">要检查的字符串</param>
       /// <param name="p_StartIndex">起始位置</param>
       /// <param name="p_Length">指定长度</param>
       /// <param name="p_TailString">用于替换的字符串</param>
       /// <returns>截取后的字符串</returns>
       public static string GetSubString(string p_SrcString, int p_StartIndex, int p_Length, string p_TailString)
       {
           string myResult = p_SrcString;

           Byte[] bComments = Encoding.UTF8.GetBytes(p_SrcString);
           foreach (char c in Encoding.UTF8.GetChars(bComments))
           {    //当是日文或韩文时(注:中文的范围:\u4e00 - \u9fa5, 日文在\u0800 - \u4e00, 韩文为\xAC00-\xD7A3)
               if ((c > '\u0800' && c < '\u4e00') || (c > '\xAC00' && c < '\xD7A3'))
               {
                   //if (System.Text.RegularExpressions.Regex.IsMatch(p_SrcString, "[\u0800-\u4e00]+") || System.Text.RegularExpressions.Regex.IsMatch(p_SrcString, "[\xAC00-\xD7A3]+"))
                   //当截取的起始位置超出字段串长度时
                   if (p_StartIndex >= p_SrcString.Length)
                       return "";
                   else
                       return p_SrcString.Substring(p_StartIndex,
                                                      ((p_Length + p_StartIndex) > p_SrcString.Length) ? (p_SrcString.Length - p_StartIndex) : p_Length);
               }
           }

           if (p_Length >= 0)
           {
               byte[] bsSrcString = Encoding.Default.GetBytes(p_SrcString);

               //当字符串长度大于起始位置
               if (bsSrcString.Length > p_StartIndex)
               {
                   int p_EndIndex = bsSrcString.Length;

                   //当要截取的长度在字符串的有效长度范围内
                   if (bsSrcString.Length > (p_StartIndex + p_Length))
                   {
                       p_EndIndex = p_Length + p_StartIndex;
                   }
                   else
                   {   //当不在有效范围内时,只取到字符串的结尾

                       p_Length = bsSrcString.Length - p_StartIndex;
                       p_TailString = "";
                   }

                   int nRealLength = p_Length;
                   int[] anResultFlag = new int[p_Length];
                   byte[] bsResult = null;

                   int nFlag = 0;
                   for (int i = p_StartIndex; i < p_EndIndex; i++)
                   {
                       if (bsSrcString[i] > 127)
                       {
                           nFlag++;
                           if (nFlag == 3)
                               nFlag = 1;
                       }
                       else
                           nFlag = 0;

                       anResultFlag[i] = nFlag;
                   }

                   if ((bsSrcString[p_EndIndex - 1] > 127) && (anResultFlag[p_Length - 1] == 1))
                       nRealLength = p_Length + 1;

                   bsResult = new byte[nRealLength];

                   Array.Copy(bsSrcString, p_StartIndex, bsResult, 0, nRealLength);

                   myResult = Encoding.Default.GetString(bsResult);
                   myResult = myResult + p_TailString;
               }
           }

           return myResult;
       }


       public static string GetStringValue(object obj, string defaultValue)
       {
           if (obj != null)
           {
               return obj.ToString();
           }
           else
           {
               return defaultValue;
           }
       }
       public static string GetInt2String(object num, int length)
       {
           int iNum = 0;
           string strFormat = "";
           if (Int32.TryParse(GetStringValue(num, ""), out iNum))
           {
               if (length > 0)
               {
                   strFormat += "{0:";
                   for (int i = 0; i < length; i++)
                   {
                       strFormat += "0";
                   }
                   strFormat += "}";
                   return string.Format(strFormat, iNum);
               }
           }
           return GetStringValue(num, "");
       }
       /// <summary>
       /// MD5函数
       /// </summary>
       /// <param name="str">原始字符串</param>
       /// <returns>MD5结果</returns>
       public static string MD5(string str)
       {
           byte[] b = Encoding.UTF8.GetBytes(str);
           b = new System.Security.Cryptography.MD5CryptoServiceProvider().ComputeHash(b);
           string ret = "";
           for (int i = 0; i < b.Length; i++)
               ret += b[i].ToString("x").PadLeft(2, '0');

           return ret;
       }
    }
}
